<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="日期" prop="date">
        <el-date-picker clearable
          v-model="queryParams.date"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="请选择日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="车次编号" prop="trainCode">
        <el-input
          v-model="queryParams.trainCode"
          placeholder="请输入车次编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查找</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['business:daily-train-carriage:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['business:daily-train-carriage:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['business:daily-train-carriage:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['business:daily-train-carriage:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 使用折叠面板展示分组数据 -->
    <el-collapse v-loading="loading">
      <el-collapse-item v-for="(group, index) in groupedCarriages" :key="index" :name="index">
        <template slot="title">
          <div class="train-group-title">
            <span class="train-code">车次: {{ group.trainCode }}</span>
            <span class="carriage-count">
              (共{{ group.carriages.length }}节车厢，
              {{ countSeatsByType(group.carriages) }})
            </span>
          </div>
        </template>

        <!-- 嵌套表格显示具体车厢信息 -->
        <el-table
          :data="group.carriages"
          :row-style="{ height: '60px' }"
          @selection-change="handleSelectionChange"
          :default-sort="{prop: 'index', order: 'ascending'}"
        >
<!--          <el-table-column show-overflow-tooltip type="selection" width="55" align="center" />-->
          <el-table-column show-overflow-tooltip label="车厢号" align="center" prop="index" sortable/>
          <el-table-column show-overflow-tooltip label="ID" align="center" prop="id" />
          <el-table-column show-overflow-tooltip label="日期" align="center" prop="date">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.date, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="车次编号" align="center" prop="trainCode" />
          <el-table-column show-overflow-tooltip label="座位类型" align="center">
            <template slot-scope="scope">
              <dict-tag :options="dict.type.seat_type" :value="scope.row.seatType"/>
            </template>
          </el-table-column>
          <el-table-column show-overflow-tooltip label="座位数" align="center" prop="seatCount" />
          <el-table-column show-overflow-tooltip label="排数" align="center" prop="rowCount"/>
          <el-table-column show-overflow-tooltip label="列数" align="center" prop="colCount"/>
<!--          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">-->
<!--            <template slot-scope="scope">-->
<!--              <el-button-->
<!--                size="mini"-->
<!--                type="text"-->
<!--                icon="el-icon-edit"-->
<!--                @click="handleUpdate(scope.row)"-->
<!--                v-hasPermi="['business:daily-train-carriage:edit']"-->
<!--              >修改</el-button>-->
<!--              <el-button-->
<!--                size="mini"-->
<!--                type="text"-->
<!--                icon="el-icon-delete"-->
<!--                @click="handleDelete(scope.row)"-->
<!--                v-hasPermi="['business:daily-train-carriage:remove']"-->
<!--              >删除</el-button>-->
<!--            </template>-->
<!--          </el-table-column>-->
        </el-table>
      </el-collapse-item>
    </el-collapse>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改每日车厢对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="日期" prop="date">
          <el-date-picker clearable
            v-model="form.date"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="请选择日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="车次编号" prop="trainCode">
          <el-input v-model="form.trainCode" placeholder="请输入车次编号" />
        </el-form-item>
        <el-form-item label="箱序" prop="index">
          <el-input-number v-model="form.index" placeholder="请输入箱序" />
        </el-form-item>
        <el-form-item label="座位类型" prop="seatType">
          <el-select v-model="form.seatType" placeholder="请选择座位类型">
            <el-option
              v-for="dict in dict.type.seat_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排数" prop="rowCount">
          <el-input-number v-model="form.rowCount" placeholder="请输入排数" />
        </el-form-item>
        <el-form-item label="列数" prop="colCount">
          <el-input-number v-model="form.colCount" placeholder="请输入列数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDailyTrainCarriageByGroup, getDailyTrainCarriage, delDailyTrainCarriage, addDailyTrainCarriage, updateDailyTrainCarriage } from "@/api/business/daily-train-carriage";

export default {
  name: "Daily-train-carriage",
  dicts: ['seat_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 每日车厢表格数据
      dailyTrainCarriageList: [],
      // 分组后的车厢数据
      groupedCarriages: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        date: null,
        trainCode: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        date: [
          { required: true, message: "日期不能为空", trigger: "blur" }
        ],
        trainCode: [
          { required: true, message: "车次编号不能为空", trigger: "blur" }
        ],
        index: [
          { required: true, message: "箱序不能为空", trigger: "blur" }
        ],
        seatType: [
          { required: true, message: "座位类型不能为空", trigger: "change" }
        ],
        rowCount: [
          { required: true, message: "排数不能为空", trigger: "blur" }
        ],
        colCount: [
          { required: true, message: "列数不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询每日车厢列表 */
    getList() {
      this.loading = true;
      listDailyTrainCarriageByGroup(this.queryParams).then(response => {
        this.groupedCarriages = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },

    // 统计各类型座位数量
    countSeatsByType(carriages) {
      if (!carriages || carriages.length === 0) {
        return "";
      }

      // 按座位类型分组统计
      const seatTypeMap = {};
      let totalSeats = 0;

      for (const carriage of carriages) {
        const seatType = carriage.seatType;
        const seatCount = carriage.seatCount || 0;
        totalSeats += seatCount;

        if (seatTypeMap[seatType]) {
          seatTypeMap[seatType] += seatCount;
        } else {
          seatTypeMap[seatType] = seatCount;
        }
      }

      // 转换为文本描述
      const result = [];
      for (const type in seatTypeMap) {
        const typeName = this.getSeatTypeName(type);
        result.push(`${typeName}: ${seatTypeMap[type]}个`);
      }

      return result.join('，') + `，总座位数: ${totalSeats}个`;
    },

    // 获取座位类型名称
    getSeatTypeName(type) {
      const seatTypes = this.dict.type.seat_type;
      if (seatTypes) {
        const found = seatTypes.find(item => item.value === type);
        if (found) {
          return found.label;
        }
      }
      return type;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        date: null,
        trainCode: null,
        index: null,
        seatType: null,
        seatCount: null,
        rowCount: null,
        colCount: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加每日车厢";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getDailyTrainCarriage(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改每日车厢";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 计算座位数 = 排数 × 列数
          this.form.seatCount = this.form.rowCount * this.form.colCount;

          if (this.form.id != null) {
            updateDailyTrainCarriage(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDailyTrainCarriage(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除每日车厢编号为"' + ids + '"的数据项？').then(function() {
        return delDailyTrainCarriage(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('business/daily-train-carriage/export', {
        ...this.queryParams
      }, `daily-train-carriage_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style>
/* 折叠面板相关样式 */
.train-group-title {
  display: flex;
  align-items: center;
  font-size: 14px;
}

.train-code {
  font-weight: bold;
  margin-right: 20px;
  min-width: 80px;
}

.carriage-count {
  color: #606266;
  font-size: 13px;
}

.el-collapse-item__header {
  height: 60px;
  line-height: 60px;
  background-color: #f5f7fa;
  padding-left: 15px;
}

.el-collapse-item__content {
  padding: 10px;
}
</style>
